package simportal.controller;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import simportal.persistent.User;
import simportal.service.UserService;

import com.cfuture08.eweb4j.component.DivPageComp;
import com.cfuture08.eweb4j.component.dwz.DWZUtil;
import com.cfuture08.eweb4j.mvc.annotation.Controller;
import com.cfuture08.eweb4j.mvc.annotation.FieldParam;
import com.cfuture08.eweb4j.mvc.annotation.Param;
import com.cfuture08.eweb4j.mvc.annotation.RequestMapping;
import com.cfuture08.eweb4j.mvc.annotation.Result;
import com.cfuture08.eweb4j.mvc.annotation.Singleton;
import com.cfuture08.eweb4j.mvc.annotation.ValField;
import com.cfuture08.eweb4j.mvc.annotation.Validator;

/**
 * 用户控制器
 * 
 * @author weiwei
 * 
 */
@Controller
@Singleton
public class UserControl {

	private static UserService service = new UserService();
	private static String model = "users";
	private static String success = DWZUtil.getSuccessJson("操作成功", "xssyyh",
			"users/list", "reloadTab", "显示所有用户信息").toString();

	/**
	 * Get方式访问login跳转到login.jsp页面
	 * 
	 * @return
	 */
	@RequestMapping("login")
	public String login() {
		return "redirect:login.jsp";
	}

	/**
	 * PUT方式处理登陆
	 * 
	 * @param user
	 * @param _authCode
	 * @param request
	 * @param out
	 * @return
	 */
	@RequestMapping(value = "login", method = "PUT", showValErr = "redirect:login.jsp")
	@Validator(value = { "required", "length"})
	@ValField(index = { 0, 1, 1 }, message = { "请输入验证码", "账号4-16位", "密码4-32位" }, name = {
			"authCode", "account", "password" })
	@FieldParam(index = { 1, 1, 2, 2 }, name = { "minLength", "maxLength",
			"minLength", "maxLength" }, value = { "4", "16", "4", "32" })
	public String doLogin(User user, @Param("authCode") String _authCode,String size,
			HttpServletRequest request, HttpSession session) {
		String input = "redirect:login.jsp";
		String success = "redirect:admin/main";
		String error = service.checkAuCode(_authCode, request);
		if (error == null) {
			error = service.login(user, _authCode, request);
			if (error == null) {
				return success;
			}
		}

		session.setAttribute("loginError", error);
		return input;
	}

	/**
	 * PUT方式处理退出登陆
	 * 
	 * @param session
	 * @param out
	 * @return
	 */
	@RequestMapping(value = "admin/logout", method = "PUT")
	public String doLogout(HttpSession session, PrintWriter out) {
		String result = "redirect:../login";
		User loginUser = (User) session.getAttribute("loginUser");
		// 修改用户状态为下线
		String error = service.update(loginUser.getId(),
				new String[] { "status" }, new String[] { "下线" });
		if (error != null) {
			out.print("退出失败，原因：" + error + "<script>history.go(-1)</script>");
			result = "ajax";
		} else {
			session.invalidate();
		}

		return result;
	}

	/**
	 * GET方式访问注册页面
	 * 
	 * @return
	 */
	@RequestMapping("register")
	public String register() {
		return "register.jsp";
	}

	/**
	 * 注册
	 * 
	 * @param user
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "register", method = "POST", showValErr = "redirect:register.jsp")
	@Validator(value = { "required", "length", "chinese" })
	@ValField(index = { 0, 0, 0, 0, 1, 1, 1, 2 }, message = { "请输入账号", "请输入密码",
			"请输入验证码", "请填写姓名", "账号4-16位", "密码4-32位", "姓名2-3位", "请填写中文姓名" }, name = {
			"account", "password", "authCode", "trueName", "account",
			"password", "trueName", "trueName" })
	@FieldParam(index = { 4, 4, 5, 5, 6, 6 }, name = { "minLength",
			"maxLength", "minLength", "maxLength", "minLength", "maxLength" }, value = {
			"4", "16", "4", "32", "2", "3" })
	public String doRegister(User user, @Param("rePass") String rePass,
			@Param("authCode") String _authCode, HttpServletRequest request,
			PrintWriter out, HttpSession session) {
		String input = "redirect:register.jsp";

		// 检查验证码
		String error = service.checkAuCode(_authCode, request);
		if (error == null) {
			// 检查重复输入的密码
			error = service.checkPassword(user.getPassword(), rePass);
			if (error == null) {
				error = service.create(user);
				if (error == null) {
					out.print("恭喜注册成功!现在就<a href='login'>登陆</a>?");
					return "ajax";
				}
			}
		}
		session.setAttribute("registerError", error);
		return input;
	}

	/**
	 * 批量删除
	 * 
	 * @param ids
	 * @param out
	 * @return
	 */
	@RequestMapping(value = "admin/users/batchRemove", method = "DELETE", showValErr = "dwzJson")
	@Validator("required")
	@ValField(name = "ids", message = "请选择要删除的信息")
	public String batchRemoveHandler(@Param("ids") Integer[] ids,
			PrintWriter out) {
		String info = null;
		String error = service.batchRemove(ids);
		if (error == null)
			info = success;
		else
			info = error;
		out.print(info);
		return null;
	}

	/**
	 * 删除
	 * 
	 * @param id
	 * @param out
	 * @return
	 */
	@RequestMapping(value = "admin/users/{id}", method = "DELETE", showValErr = "dwzJson")
	@Validator("required")
	@ValField(name = "id", message = "请选择要删除的信息")
	public String removeHandler(@Param("id") Integer id, PrintWriter out) {
		return this.batchRemoveHandler(new Integer[] { id }, out);
	}

	/**
	 * 列表显示
	 * 
	 * @param p
	 * @param n
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "admin/users/list", method = "GET|POST")
	@Result(name = { "success" }, location = { "list.jsp" })
	public String listHandler(@Param(value = "pageNum", init = "1") int p,
			@Param(value = "numPerPage", init = "20") int n,
			HttpServletRequest request) {
		List<User> pojos = service.getPage(p, n);
		if (pojos != null) {
			request.setAttribute("model", model);
			request.setAttribute("pojos", pojos);
			// 分页组件
			request.setAttribute("dpc",
					new DivPageComp(p, n, service.countAll(), 10));
			request.setAttribute("random", Math.random());
		}
		return "success";
	}

	/**
	 * 关键字查询
	 * 
	 * @param keyword
	 * @param p
	 * @param n
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "admin/users/search", method = "GET|POST")
	@Result(name = "success", location = "list.jsp")
	public String searchKeyword(@Param("keyword") String keyword, int p, int n,
			HttpServletRequest request) {
		request.setAttribute("model", model);
		request.setAttribute(
				"pojos",
				service.searchByKeywordAndPaging(new String[] { "trueName",
						"account", "status" }, keyword, p, n, 0));
		request.setAttribute("keyword", keyword);
		List<User> list = service.searchByKeywordAndPaging(new String[] {
				"trueName", "account", "status" }, keyword, -1, -1, 0);
		long count = 0;
		if (list != null) {
			count = list.size();
		}
		// 分页组件
		request.setAttribute("dpc", new DivPageComp(p, n, count, 10));
		request.setAttribute("random", Math.random());
		return "success";
	}

	/**
	 * GET|POST方式，跳转到添加页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "admin/users/new", method = "GET|POST")
	public String addHandler(HttpServletRequest request) {
		request.setAttribute("model", model);
		return "add.jsp";
	}

	/**
	 * 添加
	 * 
	 * @param pojo
	 * @param out
	 * @return
	 */
	@RequestMapping(value = "admin/users/", method = "POST", showValErr = "dwzJson")
	public String createHandler(User pojo, PrintWriter out) {
		String info = null;
		String error = service.create(pojo);
		if (error == null)
			info = success;
		else
			info = DWZUtil.getFailedJson(error).toString();
		out.print(info);
		return null;
	}

	/**
	 * GET|POST方式打开编辑页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "admin/users/{id}/edit", method = "GET|POST", showValErr = "dwzJson")
	@Validator("required")
	@ValField(message = { "请选择要编辑的信息" }, name = { "id" })
	public String editHandler(@Param("id") Integer id,
			HttpServletRequest request) {
		User pojo = service.getOne(id);
		if (pojo != null) {
			request.setAttribute("pojo", pojo);
			request.setAttribute("model", model);
		}
		return "../edit.jsp";
	}

	/**
	 * 修改
	 * 
	 * @param pojo
	 * @param out
	 * @return
	 */
	@RequestMapping(value = "admin/users/", method = "PUT", showValErr = "dwzJson")
	@Validator(value = { "required", "int" })
	@ValField(index = { 0, 1 }, message = { "请选择要编辑的信息", "排序项只能输入数字" }, name = {
			"navMenuId", "rank" })
	public String updateHandler(User pojo, PrintWriter out) {
		String info = null;
		String error = service.update(pojo, "account", "账号");
		if (error == null)
			info = success;
		else
			info = DWZUtil.getFailedJson(error).toString();
		out.print(info);
		return null;
	}
}
